package com.star.controller.admin;

import com.star.dto.DishPageQueryDTO;
import com.star.entity.Dish;
import com.star.result.PageResult;
import com.star.result.Result;
import com.star.service.DishService;
import com.star.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

/**
 * 菜品管理
 */
@RestController("adminDishController")
@RequestMapping("/admin/dish")
@Slf4j
// Swagger接口文档
@Api(tags = "管理员端菜品管理接口")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private RedisTemplate<String, List<DishVO>> redisTemplate;

    /**
     * 菜品分页查询
     * @param dishPageQueryDTO
     * @return
     */
    @GetMapping("/page")
    @ApiOperation("菜品分页查询")
    public Result<PageResult> page(DishPageQueryDTO dishPageQueryDTO){
        log.info("菜品分页查询{}",dishPageQueryDTO);
        PageResult pageResult = dishService.pageQuery(dishPageQueryDTO);
        return Result.success(pageResult);
    }

    /**
     * 根据id查询菜品
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @ApiOperation("根据id查询菜品")
    public Result<DishVO> getById(@PathVariable Long id){
        log.info("根据id查询菜品{}", id);
        DishVO dishVO = dishService.getByIdWithFlavor(id);
        return Result.success(dishVO);
    }

    /**
     * 根据菜品分类查询菜品
     * @param categoryId
     * @return
     */
    @GetMapping("/list")
    @ApiOperation("根据菜品分类查询菜品")
    public Result<List<Dish>> getByCategoryId(Long categoryId){
        log.info("根据菜品分类查询菜品{}", categoryId);
        Dish dish = new Dish();
        dish.setCategoryId(categoryId);

        List<Dish> dishes = dishService.getByCategoryId(dish);
        return Result.success(dishes);
    }
    /**
     * 更新菜品起售、停售状态
     * @param status 菜品状态
     * @param id 菜品id
     * @return
     */
    @PostMapping("/status/{status}")
    public Result<String> updateStatus(@PathVariable Integer status, Long id){
        log.info("更新菜品起售、停售状态{}{}", status, id);
        dishService.updateStatus(status, id);

        // 清除redis缓存数据
        clearDish("dish_*");

        return Result.success();
    }

    /**
     * 清除redis缓存数据
     * @param pattern
     */
    private void clearDish(String pattern){
        Set<String> keys = redisTemplate.keys(pattern);
        if(keys != null){
            redisTemplate.delete(keys);
        }
    }
}
